package com.lll.handler;

import com.lll.protocol.LoginRequestMessage;
import com.lll.protocol.LoginResponseMessage;
import com.lll.protocol.Message;
import com.lll.protocol.MessageHeader;
import com.lll.service.UserServiceFactory;
import com.lll.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<Message> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        MessageHeader header = msg.getHeader();
        if (msg.getBody() instanceof LoginRequestMessage) {
            LoginRequestMessage requestMessage = (LoginRequestMessage) msg.getBody();
            String username = requestMessage.getUsername();
            String password = requestMessage.getPassword();
            boolean login = UserServiceFactory.getUserService().login(username, password);
            LoginResponseMessage message;
            if (login) {
                SessionFactory.getSession().bind(ctx.channel(), username);
                message = new LoginResponseMessage(true, "登录成功");
            } else {
                message = new LoginResponseMessage(false, "用户名或密码不正确");
            }
            Message<LoginResponseMessage> loginResponseMessageMessage = new Message<>();
            header.setType((byte) Message.LoginResponseMessage);
            loginResponseMessageMessage.setHeader(header);
            loginResponseMessageMessage.setBody(message);
            ctx.writeAndFlush(loginResponseMessageMessage);
        }

    }
}
